package com.response; /**
 * @author wzm
 * @create 2023-03-06 16:17
 */

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;

@WebServlet("/resp04")
public class ResponseServlet04 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //当浏览器访问当前Servlet响应一个图片给浏览器
        //1.从磁盘上读取一个图片  文件输入流
        FileInputStream fis = new FileInputStream("e://down.jpeg");

        //2.使用Servlet的字节输出流将二进制数据向浏览器响应
        ServletOutputStream os = response.getOutputStream();

        //3.将输入流读取的数据复制给输出流 让他进行输出
        //声明数组存储每次读取的数据
        byte[] buff = new byte[1024];
        //定义一个长度存储每次读取的结果
        int len = 0;
        //循环读取数据 存放在数组中 如果没有读到数据返回-1
        while((len = fis.read(buff)) != -1){
            //将每次读取到的数据一点点写到（响应）到浏览器
            os.write(buff,0,len);
        }

        //4.关闭资源  只需要关闭输入流  response的输出流执行完毕自己会关
        fis.close();

    }
}
